Sum of root to leaf binary numbers¶
Time: O(N); Space: O(H); easy
Given a binary tree, each node has value 0 or 1. Each root-to-leaf path represents a binary number starting with the most significant bit.
For example, if the path is 0 -> 1 -> 1 -> 0 -> 1, then this could represent 01101 in binary, which is 13.
For all leaves in the tree, consider the numbers represented by the path from the root to that leaf.
Return the sum of these numbers.
Example 1:
1
/ \
0 1
/ \ / \
0 1 0 1
Input: root = {TreeNode} [1,0,1,0,1,0,1]
Output: 22
Explanation:
= 4 + 5 + 6 + 7 = 22
Constraints:
The number of nodes in the tree is between 1 and 1000.
node.val is 0 or 1.
The answer will not exceed 2^31 - 1.
Hints:
Find each path, then transform that path to an integer in base 10.
[1]:
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
[2]:
class Solution1(object):
"""
Time: O(N)
Space: O(H)
"""
def sumRootToLeaf(self, root):
"""
:type root: TreeNode
:rtype: int
"""
M = 10**9 + 7
def sumRootToLeafHelper(root, val):
if not root:
return 0
val = (val*2 + root.val) % M
if not root.left and not root.right:
return val
return (sumRootToLeafHelper(root.left, val) +
sumRootToLeafHelper(root.right, val)) % M
return sumRootToLeafHelper(root, 0)
[3]:
s = Solution1()
root = TreeNode(1)
root.left, root.right = TreeNode(0), TreeNode(1)
root.left.left, root.left.right = TreeNode(0), TreeNode(1)
root.right.left, root.right.right = TreeNode(0), TreeNode(1)
assert s.sumRootToLeaf(root) == 22